<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Models\Material;
use Intervention\Image\Facades\Image;

class MaterialController extends ApiController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadImage(){
        if ($file = $this->request->file('file')) {
            $img = Image::make($file->getRealPath());
            $image = [
                'uid'=>$this->uid,
                'username'=>$this->username,
                'type'=>'image',
                'created_at'=>time(),
                'updated_at'=>time(),
                'extension'=>$file->extension(),
                'size'=>$file->getSize(),
                'name'=>$file->getClientOriginalName(),
                'width'=>$img->width(),
                'height'=>$img->height()
            ];

            $filename  = $file->hashName();
            $imagePath = 'image/'.date('Y').'/'.date('m').'/'.$filename;
            $thumbPath = 'thumb/'.date('Y').'/'.date('m').'/'.$filename;

            //大图
            if ($img->getWidth() > 1600) {
                $scale = 1600/$img->getWidth();
                @mkdir(dirname(storage_public_path($imagePath)), 0777, true);
                $img->resize(1600, $img->getHeight()*$scale)->save(storage_public_path($imagePath));
            } else {
                $img->save(storage_public_path($imagePath));
            }

            //缩略图
            if ($img->getWidth() > 500){
                $scale = 500/$img->getWidth();
                @mkdir(dirname(storage_public_path($thumbPath)), 0777, true);
                $img->resize(500, $img->getHeight()*$scale)->save(storage_public_path($thumbPath));
            } else {
                $img->save(storage_public_path($thumbPath));
            }

            $image['source'] = $imagePath;
            $image['thumb']  = $thumbPath;

            $image['id'] = Material::insertGetId($image);
            $image['image'] = $imagePath;
            $image['imageurl'] = image_url($imagePath);
            $image['thumburl'] = image_url($thumbPath);

            unset($image['source']);
            return ajaxReturn(['image'=>$image]);
        }else {
            return ajaxError(1, 'upload image fail');
        }
    }
}
